<?php
namespace TwinPeaks\Lib;
require_once __DIR__ . '/../core/trait/TSingleton.php';

use TwinPeaks\Core as Core;

abstract class CDb
{
	use Core\TSingleton;
	
	/**
	 * @var PDO PDO connection object
	 */
	private $pdoConnect;
	
	/**
	 * Returns connection string to main database.
	 * 
	 * @abstract
	 * @static
	 * @access public
	 * @return string
	 */
	abstract static function getDefaultNode();
	
	/**
	 * @abstract
	 * @access public
	 * @return string
	 */
	abstract function getDSNByNodeId($nodeId);
	
	/**
	 * Returns database user name.
	 * 
	 * @abstract
	 * @access public
	 * @return string
	 */
	abstract function getUsername();
	
	/**
	 * Returns database user passsword.
	 * 
	 * @static
	 * @access public
	 * @return string
	 */
	abstract function getPass();
	
	/**
	 * Returns PDO driver options. None by default.
	 * 
	 * @access public
	 * @return array
	 */
	function getPDODriverOptions()
	{
		return [];
	}
	
	/**
	 * @return void 
	 */
	protected function onCreate()
	{
		$args = func_get_args();
		$nodeId = $args[0];
		
		try
		{
			$dsn = $this->getDSNByNodeId($nodeId);
			$this->pdoConnect = new PDO($dsn, $this->getUsername(), $this->getPass(),
				$this->getPDODriverOptions());
		}
		catch(\PDOException $pdoExcep)
		{
		}
	}
	
	/**
	 * @static
	 * @final
	 * @return CDb
	 */
	static function connect($node = null)
	{
		if ($node === null)
			$node = static::getDefaultNode();
		
		return self::getInstance($node);
	}
	
	/**
	 * @final
	 * @static
	 * @access public
	 * @return true
	 */
	static function useParametricInstantiation()
	{
		return true;
	}	
}
